<template>
  <view class="message-list-page">
    <nut-list :listData="messageList" :height="90">
      <template v-slot:default="{ item }">
        <nut-cell class="message-item" @click="goToChat(item)">
          <template v-slot:default>
            <view class="item-content">
              <nut-avatar size="large" :icon="item.service_person_avatar" />
              <view class="item-text">
                <view class="item-title">{{ item.service_person_name }}</view>
                <view class="item-subtitle">{{ item.last_message_content }}</view>
              </view>
              <view class="item-meta">
                <view class="item-time">{{ item.last_message_time_str }}</view>
                <!-- 可以添加未读消息标记 -->
                <!-- <nut-badge :value="item.unreadCount" v-if="item.unreadCount > 0"></nut-badge> -->
              </view>
            </view>
          </template>
        </nut-cell>
      </template>
    </nut-list>
    <view v-if="messageList.length === 0" class="empty-state">
      <nut-empty description="暂无消息"></nut-empty>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import { searchDemand1, searchDemand2 } from "@/api/message.ts";

// 模拟消息列表数据
const messageList = ref([]);
const userType = ref(uni.getStorageSync("usertype") || "customer");

// 轮询定时器
let pollingTimer: number | null = null;
const POLLING_INTERVAL = 5000; // 5秒轮询一次

// 跳转到聊天界面
const goToChat = (item: string[]) => {
  console.log("传递的数组", item);
  // 并确保传递必要的参数，例如 servicePersonId 或 conversationId
  uni.navigateTo({
    // Use uni.navigateTo directly
    url: `/pages/chat/index?item=${JSON.stringify(item)}`,
  });
};

// 获取消息列表
const fetchMessageList = async () => {
  try {
    const userId = uni.getStorageSync("userId");
    let res: any;
    if (userType.value === "customer") {
      res = await searchDemand1(userId);
    } else {
      res = await searchDemand2(userId);
    }
    messageList.value = res.data;
  } catch (error) {
    console.error("Failed to fetch message list:", error);
    uni.showToast({ title: "加载消息失败", icon: "none" });
  }
};

// 开始轮询
const startPolling = () => {
  fetchMessageList(); // 立即执行一次
  pollingTimer = setInterval(fetchMessageList, POLLING_INTERVAL);
};

// 停止轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer);
    pollingTimer = null;
  }
};

onMounted(() => {
  startPolling();
});

onUnmounted(() => {
  stopPolling();
});
</script>

<style lang="scss" scoped>
.message-list-page {
  min-height: 150vh;
}

.message-item {
  // 移除 NutUI Cell 的默认内边距，以便自定义布局
  ::v-deep(.nut-cell__title) {
    padding: 0;
  }
  ::v-deep(.nut-cell__value) {
    padding: 0;
  }
  ::v-deep(.nut-cell__left-icon-wrap) {
    margin-right: 0; // 移除左侧图标默认间距（如果未使用）
  }

  .item-content {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 12px 16px; // 调整内边距
    box-sizing: border-box;
  }

  .item-text {
    flex: 1;
    margin-left: 12px; // 头像和文字间距
    overflow: hidden; // 防止文字过长溢出
  }

  .item-title {
    font-size: 16px;
    color: #333;
    font-weight: 500; // 加粗一点
    margin-bottom: 4px; // 标题和副标题间距
  }

  .item-subtitle {
    font-size: 13px;
    color: #888;
    white-space: nowrap; // 不换行
    overflow: hidden;
    text-overflow: ellipsis; // 溢出显示省略号
  }

  .item-meta {
    display: flex;
    flex-direction: column;
    align-items: flex-end; // 右对齐
    margin-left: 12px; // 文字和元信息间距
  }

  .item-time {
    font-size: 12px;
    color: #999;
    margin-bottom: 6px; // 时间和未读标记间距
  }
}

.empty-state {
  padding-top: 100px; // 让空状态居中一些
}
</style>
